package com.uduemc.jcms.backend.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.uduemc.jcms.backend.BackendModule;
import com.uduemc.jcms.generate.entity.JcmsBackendUser;
import com.uduemc.jcms.generate.service.IJcmsBackendUserService;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;

@Component
public class BackendLoginInterceptor implements HandlerInterceptor {

	@Autowired
	ApplicationContext applicationContext;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		String attribute = (String) session.getAttribute(BackendModule.BackendUserIdSession);

		if (StrUtil.isNotBlank(attribute) && NumberUtil.isNumber(attribute)) {
			Long bUserId = Long.valueOf(attribute);
			if (bUserId != null && bUserId.longValue() > 0) {
				IJcmsBackendUserService jcmsBackendUserServiceImpl = (IJcmsBackendUserService) applicationContext.getBean("jcmsBackendUserServiceImpl");
				JcmsBackendUser backendUser = jcmsBackendUserServiceImpl.getById(bUserId);
				session.setAttribute(BackendModule.BackendUserSession, backendUser);
				return true;
			}
		}

		response.sendRedirect(BackendModule.LoginUri);
		return false;
	}
}
